package com.woniu.p2p.advice;

import com.woniu.p2p.entity.*;
import com.woniu.p2p.service.SystemRecordService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;


@Aspect
@Component
public class MyAdvice {

    @Autowired
    private SystemRecordService systemRecordService;


    /**
     * @param proceedingJoinPoint
     * @return 用户登录日志
     * @throws Throwable
     */
    @Around("execution(* com.woniu.p2p.controller.P2PUserController.checkLogin(..))")
    public User aroundCheckLogin(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        System.out.println("环绕前");
        User user = (User) proceedingJoinPoint.proceed();
        System.out.println("环绕后");
        if (user == null)
            return null;
        else {
            UserRecord userRecord = new UserRecord();
            userRecord.setUserId(user.getUserId());
            userRecord.setUserName(user.getUserRealname());
            userRecord.setRecordTime(new Date(System.currentTimeMillis()));
            userRecord.setRecordIp(this.getIpAddress(request));
            systemRecordService.addUserRecord(userRecord);
        }
        return user;
    }


    /**
     * 管理员登录日志
     */
    @AfterReturning("execution(* com.woniu.p2p.behindController.AdminController.login(..))")
    public void afterLogin() {
        System.out.println("登录");
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = request.getSession();
        Admin loginUser = (Admin) session.getAttribute("userInfo");
        if (loginUser != null) {
            AdminRecord adminRecord = new AdminRecord();
            adminRecord.setRecordType("登录");
            adminRecord.setAdminName(loginUser.getAdminAccount());
            adminRecord.setRecordIp(this.getIpAddress(request));
            adminRecord.setAdminId(loginUser.getAdminId());
            adminRecord.setRecordTime(new Date(System.currentTimeMillis()));
            systemRecordService.addAdminRecord(adminRecord);
        }
    }

    /**
     * 管理员退出日志
     */
    @Before("execution(* com.woniu.p2p.behindController.AdminController.logout(..))")
    public void beforeLogout() {
        System.out.println("退出");
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = request.getSession();
        Admin loginUser = (Admin) session.getAttribute("userInfo");
        if (loginUser != null) {
            AdminRecord adminRecord = new AdminRecord();
            adminRecord.setRecordType("注销");
            adminRecord.setAdminName(loginUser.getAdminAccount());
            adminRecord.setRecordIp(this.getIpAddress(request));
            adminRecord.setAdminId(loginUser.getAdminId());
            adminRecord.setRecordTime(new Date(System.currentTimeMillis()));
            systemRecordService.addAdminRecord(adminRecord);
        }
    }


    @AfterReturning("execution(* com.woniu.p2p.behindController.*.*(..))")
    public void afterOperation(JoinPoint joinPoint) {

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = request.getSession();
        Admin loginUser = (Admin) session.getAttribute("userInfo");
        if (loginUser != null) {
            String name = joinPoint.getSignature().getName();
            OperationRecord operationRecord = new OperationRecord();
            operationRecord.setOperationTime(new Date(System.currentTimeMillis()));
            switch (joinPoint.getSignature().toShortString()) {
                case "CouponController.deletebyid":
                    System.out.println("删除优惠券");
                    operationRecord.setOperationName("删除优惠券");
                    break;
                case "CouponController.addcoupon":
                    System.out.println("增加优惠券");
                    operationRecord.setOperationName("增加优惠券");
                    break;
                case "CouponController.exportcoupon":
                    System.out.println("导出优惠券");
                    operationRecord.setOperationName("导出优惠券");
                    break;
                case "ManageController.changeStatus()":
                    System.out.println("改变用户状态");
                    operationRecord.setOperationName("改变用户状态");
                    break;
                case "ScoreController.deletebyid":
                    System.out.println("删除积分");
                    operationRecord.setOperationName("删除积分");
                    break;
                case "ScoreController.addscore":
                    System.out.println("新增积分");
                    operationRecord.setOperationName("新增积分");
                    break;
                case "ScoreController.piliangdel":
                    System.out.println("批量删除积分");
                    operationRecord.setOperationName("批量删除积分");
                    break;
                case "UserChargeController.insert":
                    System.out.println("用户充值");
                    operationRecord.setOperationName("用户充值");
                    break;
                default:
                    return;

            }
            operationRecord.setUserId(loginUser.getAdminId());
            operationRecord.setUserName(loginUser.getAdminAccount());

            systemRecordService.addOperationRecord(operationRecord);
        }
    }


    public String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = ip.indexOf(",");
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        }
        ip = request.getHeader("X-Real-IP");
        if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            return ip;
        }
        return request.getRemoteAddr();
    }

}
